package com.wyx.Controller;

import com.wyx.Common.R;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;

/**
 * 图片上传下载模块
 */
@RestController
@RequestMapping("/common")
public class commonController {
    @Value("${eagle.path}")
    private String path;
    private ServletOutputStream outputStream;

    /**
     * 将用户提交的文件下载到指定目录
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //原始文件名
        String originalFilename = file.getOriginalFilename();
        //获取后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //随机文件名 使用UUID
        String filename = UUID.randomUUID().toString() + substring;
        File dir = new File(path);
        //如果不存在文件夹就创建
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            //文件复制
            file.transferTo(new File(path + filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(filename);
    }
    //将图片上传到页面
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            FileInputStream fis=new FileInputStream(path+name);
            ServletOutputStream outputStream = response.getOutputStream();
            int len=0;
            byte[]bytes=new byte[1024];
            while ((len=fis.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            fis.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
